<?php
/*
  Microblog bot for game release notifications
  Copyright (C) 2017  Alexander Yakovlev

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace Source;

use \Game;
use \PHPHtmlParser\Dom;

class Steam extends Source {
  public $title = "Steam";
  protected function parse_tag($tag) {
    $url = 'http://store.steampowered.com/search/';
    $url .= '?'.http_build_query([
      'sort_by' => 'Released_DESC',
      'term' => $tag,
      'displayterm' => $tag,
      'category1' => 998, // only games
    ]);
    try {
      $text = $this->get_text($url);
      $this->dom->loadStr($text, []);
    } catch (\Exception $e) {
      echo $e->getMessage();
      echo $e->getTraceAsString();
      return "";
    }
    unset($text);
    $games = $this->dom->find('#search_result_container a.search_result_row');
    foreach ($games as $gameLink) {
      $url = $gameLink->getAttribute('href');
      $url = substr($url,0,strpos($url, '?')); // remove query string
      $game = new Game;
      $game->url = $url;
      try {
        $text = $this->get_text($url);
        $this->dom = new Dom;
        $this->dom->loadStr($text, []);
        unset($text);
        $name = $this->dom->find('div.apphub_AppName');
        $description = $this->dom->find('meta[property=og:description]');
        try {
          $game->title = $name->innerHtml;
          $game->description = $description->innerHtml;
        } catch (\Exception $e) {
          echo 'No title or description found for '.$url.PHP_EOL;
        }
      } catch (\Exception $e) {
        echo $e->getMessage();
        echo $e->getTraceAsString();
      }
      $this->games[] = $game;
    }
  }
  protected function parse() {
    $this->parse_tag("text-based");
  }
}
